<template>
  <div>
    <!-- 头部 -->
    <a-form
      ref="searchRef"
      :model="searchForm"
      :hideRequiredMark="true"
      style="margin-bottom: 20px"
    >
      <a-row>
        <a-col :span="6">
          <a-form-item label="上线时间：">
            <a-range-picker @change="panelChange"></a-range-picker>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-form-item name="saleValue" label="状态：">
            <a-select
              ref="select"
              v-model:value="searchForm.status"
              @focus="focus"
              @change="handleChange"
              placeholder="请选择状态"
              allowClear
            >
              <a-select-option
                v-for="item in saleStatusOptions"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item name="saleValue" label="关键字">
            <a-input
              placeholder="根据关键字进行查询"
              v-model:value="searchForm.keyWord"
              allowClear
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="2" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center"
            >搜索</a-button
          >
        </a-col>
        <a-button @click="reset" class="d-a-center">重置</a-button>
      </a-row>
    </a-form>

    <!-- 列表 -->
    <a-table
      rowKey="id"
      :columns="columns"
      :row-selection="rowSelection"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #title
        ><a-button
          type="primary"
          @click="add"
          v-has="{ a: $route, b: 2 }"
          class="d-a-center"
          >新增</a-button
        ></template
      >
      <template #status="{ record }">
        <div>
          {{ ["进行中", "已结束", "未开始"][record.status] }}
        </div>
      </template>
      <template #stack="{ record, index }">
        <div
          v-has="{ a: $route, b: 2 }"
          @click="changeStack(record.status, index, record.id)"
        >
          <a-switch
            v-model:checked="record.status"
            :checkedValue="0"
            :unCheckedValue="1"
          />
        </div>
      </template>
      <template #operation="{ record }">
        <a-button
          type="link"
          @click="handleActive(record)"
          v-has="{ a: $route, b: 2 }"
        >
          激活明细</a-button
        >
        <a-button
          type="link"
          danger
          @click="handleLook(record)"
          v-has="{ a: $route, b: 1 }"
          >查看</a-button
        >
        <a-button
          type="link"
          style="color: #35c0f2"
          v-has="{ a: $route, b: 1 }"
          @click="editHuli(record)"
          >编辑</a-button
        >
        <!-- v-if="upstate" -->
        <a-button
          type="link"
          v-has="{ a: $route, b: 1 }"
          @click="upLine(record)"
					v-if="record.status === 2"
          >上线</a-button
        >
      </template>
    </a-table>
    <!-- 多项删除 -->
    <a-button
      type="danger"
      @click="excleData"
      v-has="{ a: $route, b: 2 }"
      class="d-a-center"
      >导出</a-button
    >

    <div>
      <!-- 新增/查看-->
      <a-modal
        width="92%"
        v-model:visible="visible"
        :title="title"
        @ok="saveRight"
        @cancle="cancleOrder('visible')"
      >
        <template #footer>
          <div class="d-j-around">
            <a-button @click="cancleOrder('visible')" class="d-a-center"
              >关闭</a-button
            >
            <a-button
              v-if="title != '查看'"
              type="primary"
              @click="saveRight"
              class="d-a-center"
              >保存</a-button
            >
          </div>
        </template>
        <div class="header fl" v-if="title == '查看'">
          <div
            class="tab"
            :class="{ active: active == index }"
            v-for="(item, index) in tab"
            :key="index"
            @click="hanldeMyActive(index)"
          >
            {{ item.name }}
          </div>
        </div>

        <a-form
          v-if="(title == '查看' && active == 0) || title != '查看'"
          ref="formRef"
          style="padding-top: 20px"
          :model="orderForm"
          :rules="rules1"
          :hideRequiredMark="true"
          :label-col="labelCol"
        >
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="name" label="护理卡名称">
                <a-input
                  v-model:value="orderForm.name"
                  maxLength="10"
                  placeholder="请输入护理卡名称"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="type" label="护理卡类型">
                <a-select
                  ref="select"
                  v-model:value="orderForm.type"
                  @focus="focus"
                  @change="handleChange"
                  placeholder="请选择护理卡类型"
                  allowClear
                >
                  <a-select-option
                    v-for="item in huliTypeOptions"
                    :value="item.id"
                    :key="item.id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="num" label="发放数量">
                <a-input
                  maxLength="10"
                  v-model:value="orderForm.num"
                  placeholder="请输入护理卡数量"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item label="营业额">
                <a-input
                  v-model:value="orderForm.businessPrice"
                  placeholder="请输入合计产生的营业额"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item label="激活有效期">
                <a-input
                  v-model:value="orderForm.activateDay"
                  placeholder="请输入激活有效期"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item label="使用有效期">
                <a-select
                  ref="select"
                  v-model:value="orderForm.useDay"
                  @focus="focus"
                  @change="useTimeChange"
                  placeholder="请选择使用有效期"
                  allowClear
                >
                  <a-select-option
                    v-for="item in useTimeOptions"
                    :value="item.id"
                    :key="item.id"
                    >{{ item.name }}</a-select-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <!-- 	<a-row :gutter="20" v-if="title == '查看'">
						<a-col :span="12" :lg="12" :xs="10">
							<a-form-item name="" label="创建时间">
								<a-input v-model:value="orderForm.submitTime" placeholder=""></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12" :lg="12" :xs="10">
							<a-form-item name="" label="上线时间">
								<a-input v-model:value="orderForm.createdAt" placeholder=""></a-input>
							</a-form-item>
						</a-col>
					</a-row> -->
          <a-row :gutter="20">
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item name="remark" label="备注信息">
                <a-input
                  maxLength="100"
                  v-model:value="orderForm.remark"
                  placeholder="请输入备注信息"
                ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12" :lg="12" :xs="10">
              <a-form-item label="等待期">
                <a-input
                  v-model:value="orderForm.waitNum"
                  placeholder="请输入等待期"
                ></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12" :lg="12" :xs="10" v-if="!editing">
              <a-form-item name="remark" label="居家护理">
                <span v-for="item in serviceList" :key="item.id">{{
                  item.comboServiceName + "*" + item.comboServiceCount + ","
                }}</span>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <a-card title="兑换权益" v-if="editing">
          <h4>居家护理</h4>
          <h5>服务项目 <a-button @click="addServeVisible">+</a-button></h5>
          <a-table
            v-if="serviceList.length > 0"
            :columns="columnsService"
            :data-source="serviceList"
          >
            <template #operation="{ record, index }">
              <a-button type="link" danger @click="closelog(index, record.id)"
                >删除</a-button
              >
            </template>
          </a-table>
        </a-card>
      </a-modal>
      <!-- 新增服务 -->
      <a-modal
        width="800px"
        v-model:visible="serveVisible"
        title="居家护理"
        @ok="serveVisible = false"
        @cancle="cancleOrder('serveVisible')"
      >
        <template #footer>
          <div class="d-j-around">
            <a-button @click="cancleOrder('serveVisible')" class="d-a-center"
              >取消</a-button
            >
            <a-button
              type="primary"
              @click="serveVisible = false"
              class="d-a-center"
              >确定</a-button
            >
          </div>
        </template>
        <!-- 头部 -->
        <div class="search">
          <a-form
            style="padding-top: 20px"
            :model="searchForm"
            :hideRequiredMark="true"
            :label-col="labelCol"
          >
            <a-row :gutter="20">
              <a-col :span="6" :lg="5" :md="7" :xs="20">
                <a-form-item name="nickName" label="">
                  <a-input
                    v-model:value="serviceForm.serviceName"
                    placeholder="根据服务名称模糊搜索"
                    allowClear
                  ></a-input>
                </a-form-item>
              </a-col>
              <a-col :span="2" :lg="2" :xs="5">
                <a-button type="primary" @click="handleSearch">查询</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div style="margin-top: -15px">
          <a-tag
            closable
            @close="closelog(index, item.id)"
            v-for="(item, index) in serviceList"
            :key="item.id"
            style="margin-top: 5px"
            >{{ item.name }}*{{ item.num }}</a-tag
          >
        </div>
        <div style="height: 10px" v-if="serviceList.length > 0"></div>
        <a-table
          :columns="columnsService"
          :data-source="servicesList"
          bordered
          :loading="loading"
          :pagination="paginations"
          @change="handleTableChanges1"
        >
          <template #consumables="{ record }">
            <div>
              {{ record.consumables[0].bleName }}
            </div>
          </template>
          <template #classify="{ record }">
            <div v-if="record.serviceId">
              {{ record.serviceId }}
            </div>
          </template>
          <template #num="{ record, index }">
            <div>
              <span v-if="record.add">{{ record.num }}</span>
              <a-input-number
                v-else
                id="inputNumber"
                v-model:value="record.num"
                :min="1"
              />
            </div>
          </template>
          <template #operation="{ record }">
            <a-button
              type="link"
              danger
              @click="edit(record)"
              v-has="{ a: $route, b: 2 }"
              >{{ record.add ? "已添加" : "添加" }}</a-button
            >
          </template>
        </a-table>
      </a-modal>
      <!-- 激活明细 -->
      <a-modal
        width="800px"
        v-model:visible="jihuoVisible"
        title="明细"
        @cancle="cancleOrder('jihuoVisible')"
      >
        <!-- 线上订单 、线下订单 -->
        <a-row style="margin: 0 0 30px 0" class="d-a-center">
          <div v-for="(item, index) in tabs" :key="item.id">
            <a-col :span="6">
              <a-tag
                :color="item.id == orderAct ? 'blue' : ''"
                @click="changeOrder(item.id)"
                >{{ item.title }}</a-tag
              >
            </a-col>
          </div>
          <a-col>
            <!-- 头部 -->
            <a-form
              ref="searchRef"
              :model="searchForm1"
              :hideRequiredMark="true"
            >
              <a-row class="d-a-center">
                <a-col class="d-a-center">
                  <a-form-item
                    name="saleValue"
                    label=""
                    class="d-a-center"
                    style="margin-top: 24px"
                  >
                    <a-input
                      placeholder="根据卡号模糊搜索"
                      v-model:value="searchForm1.cardNum"
                      allowClear="true"
                      class="d-a-center"
                    ></a-input> </a-form-item
                ></a-col>
                <a-col>
                  <a-button type="primary" @click="searchs" class="d-a-center"
                    >查询</a-button
                  >
                </a-col>
              </a-row>
            </a-form>
          </a-col>
        </a-row>
        <a-table
          :columns="
            orderAct == 1 ? columns1 : orderAct == 2 ? columns3 : columns2
          "
          :data-source="listRights"
          bordered
          :loading="loading"
          :pagination="paginations"
          @change="handleTableChanges"
          style="margin-top: -10px"
        >
          <template #status="{ record }">
            <div>{{ orderListStatus(record.status) }}</div>
          </template>
          <template #status1="{ record }">
            <div>{{ ComsumeStatus(record.status) }}</div>
          </template>
          <template #operation="{ record }">
            <a-button
              type="link"
              @click="handleFreeze(record.id)"
              v-has="{ a: $route, b: 2 }"
              >冻结</a-button
            >
          </template>
        </a-table>
      </a-modal>
    </div>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  computed,
  createVNode,
  watch,
  toRefs,
  unref,
  toRaw,
  isReactive,
  toRef,
} from "vue";
import {
  CheckOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { times1 } from "@/utils/dict.js";
import { Modal, message } from "ant-design-vue";
import {
  selectAllConsumableBag,
  upOrDownConsumableBag,
  selectAllDetail,
  updateAndAddConsumableBag,
  deleteConsumableBag,
} from "@/api/consume/index.js";
import * as api from "@/api/market/hulicard.js";
import { deleteObjBlank } from "@/assets/js/common.js";
import { useModal,useSelects } from "@/hooks"

// import { ifStatement } from "@babel/types";
export default {
  setup() {
    const searchRef = ref("");
    const formRef = ref("");

    const data = reactive({
      upstate: "",
      active: 0,
      editing: true,
      title: "创建",
      serveVisible: false,
      jihuoVisible: false,
      list: [],
      listRights: [], //明细列表
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {},
      times1,
      form: {},
      activeChart: "activateCount",
      myid: -1,
      trendDataAnalysis: {},
      chartData: {},
      chartTabs: [
        {
          name: "成功激活",
          value: "activateCount",
        },
        {
          name: "成功使用",
          value: "useCount",
        },
      ],
      nurseDataAnalysis: {},
      searchForm: {},
      searchForm1: {},
      number: "", //当前机构编号
      typeList: [],
      servicesList: [],
      orderForm: {
        useDay: "",
        waitNum: "",
      },
      serviceForm: {},
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      orderAct: 1, //1线上 2线下
      tabs: [
        {
          title: "已激活",
          id: 1,
        },
        {
          title: "未激活",
          id: 0,
        },
        {
          title: "已冻结",
          id: 2,
        },
      ],
    });

    const rules1 = {
      name: [
        {
          required: true,
          message: "",
        },
      ],
      type: [
        {
          required: true,
          message: "",
        },
      ],
      num: [
        {
          required: true,
          message: "",
        },
        {
          pattern: /^[0-9]*[1-9][0-9]*$/,
          // /^\+?[1-9]\d*$/,
          message: "大于0的正整数",
          trigger: ["change", "blur"],
        },
      ],
      // activateDay: [{
      // 		required: true,
      // 		message: ""
      // 	},
      // 	{
      // 		pattern: /^([1-9]\d*|[0]{1,1})$/,
      // 		message: "请输入整数",
      // 		trigger: ["change", "blur"],
      // 	},
      // ],
      // useDay: [{
      // 		required: true,
      // 		message: ""
      // 	},
      // 	{
      // 		pattern: /^([1-9]\d*|[0]{1,1})$/,
      // 		// /^\+?[1-9]\d*$/,
      // 		message: "请输入整数",
      // 		trigger: ["change", "blur"],
      // 	},
      // ],
    };

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    const pages = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const saleStatusOptions = reactive([
      {
        name: "全部",
        id: "",
      },
      {
        name: "进行中",
        id: "0",
      },
      {
        name: "已结束",
        id: 1,
      },
    ]);
    const useTimeOptions = reactive([
      {
        name: "一年期",
        id: 365,
      },
      {
        name: "三年期",
        id: 1095,
      },
      {
        name: "五年期",
        id: 1825,
      },
      {
        name: "十年期",
        id: 3650,
      },
    ]);
    const huliTypeOptions = reactive([
      {
        name: "个人版",
        id: 0,
      },
      {
        name: "家庭版",
        id: 1,
      },
    ]);
    const retComputed = {
      options: computed(() => {
        return {
          title: {
            text: "趋势分析",
          },
          tooltip: {
            trigger: "axis",
          },
          // legend: {
          //   // data: ["本月"],
          // },
          grid: {
            left: "0%",
            right: "0%",
            bottom: "0%",
            // top:'12%',
            containLabel: true,
          },
          // toolbox: {
          //   feature: {
          //     saveAsImage: {},
          //   },
          // },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: data.chartData.xAxis,
          },
          yAxis: {
            type: "value",
          },
          series: [
            {
              type: "line",
              smooth: true,
              stack: "Total",
              data: data.chartData.yAxis,
            },
          ],
        };
      }),
    };
    const delListId = ref([]); //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index;
      data.searchForm.status = status;
      page.current = 1;
      init();
    };
    // 查询
    const search = () => {
      page.current = 1;
      rowSelection.selectedRowKeys = []
      init();
    };
    const searchs = () => {
      pages.current = 1;
      initRightList();
    };
    const columns = [
      {
        title: "编号",
        dataIndex: "id",
        className: "table",
        align: "center",
      },
      {
        title: "名称",
        dataIndex: "name",
        className: "table",
        align: "center",
      },
      {
        title: "类型",
        dataIndex: "type",
        className: "table",
        slots: {
          customRender: "type",
        },
        align: "center",
      },
      {
        title: "发放数量",
        dataIndex: "num",
        className: "table",
        align: "center",
      },
      {
        title: "激活数量",
        dataIndex: "activateNum",
        className: "table",
        align: "center",
      },
      {
        title: "使用数量",
        dataIndex: "useNum",
        className: "table",
        align: "center",
      },
      {
        title: "上线时间",
        dataIndex: "createdAt",
        className: "table",
        align: "center",
      },
      {
        title: "状态",
        dataIndex: "status",
        className: "table",
        slots: {
          customRender: "status",
        },
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
        align: "center",
      },
    ];
    const columnsService = [
      {
        title: "服务项目",
        dataIndex: "name",
        className: "table",
        align: "center",
      },
      {
        title: "服务价格/次",
        dataIndex: "price",
        className: "table",
        align: "center",
      },
      {
        title: "服务次数",
        dataIndex: "num",
        className: "table",
        align: "center",
        slots: {
          customRender: "num",
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
        align: "center",
      },
    ];
    const columns1 = [
      {
        title: "卡号",
        dataIndex: "cardNum",
        className: "table",
        align: "center",
      },
      {
        title: "激活用户",
        dataIndex: "userName",
        className: "table",
        align: "center",
        sort: true,
      },
      {
        title: "用户id",
        dataIndex: "userId",
        className: "table",
        align: "center",
      },
      {
        title: "激活时间",
        dataIndex: "updatedAt",
        className: "table",
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        align: "center",
        fixed: "right",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const columns2 = [
      {
        title: "卡号",
        dataIndex: "cardNum",
        className: "table",
        align: "center",
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        align: "center",
        fixed: "right",
        slots: {
          customRender: "operation",
        },
      },
    ];
    const columns3 = [
      {
        title: "卡号",
        dataIndex: "cardNum",
        className: "table",
        align: "center",
      },
      {
        title: "操作人",
        dataIndex: "freezeName",
        className: "table",
        align: "center",
      },
    ];
    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));
    const paginations = computed(() => ({
      current: pages.current,
      pageSize: pages.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: pages.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));
    // 分页器改变的时候
    const handleTableChanges = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      pages.current = pagination.current;
      pages.pageSize = pagination.pageSize;

      // 请求列表接口
      initRightList();
    };
    const handleTableChanges1 = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      pages.current = pagination.current;
      pages.pageSize = pagination.pageSize;

      // 请求列表接口
      initService();
    };

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      init();
    };
    const cancel = () => {
      data.visible = false;
      title.value = "";
      data.orderForm = {};
      data.consumables = [];
    };
    // 新增
    const add = () => {
      data.editing = true;
      data.orderForm = {
        useDay: "",
        waitNum: "",
        businessPrice: "",
        remark: "",
      };
      data.serviceList = [];
      data.title = "创建";
      data.visible = true;
    };
    //编辑
    const editHuli = (item) => {
      data.visible = true;
      data.title = "编辑";
      data.EditDisable = !data.EditDisable;
      //显示表格
      api
        .selectNurseCardById({
          id: item.id,
        })
        .then((res) => {
          if (res.success) {
            if (res.object.type == 0 || res.object.type == "个人版") {
              res.object.type = "个人版";
            } else {
              res.object.type = "家庭版";
            }
            data.orderForm = {
              ...res.object,
            };

            data.orderForm.goodDiscount = res.object.goodList[0].goodDiscount;
            res.object.goodList.forEach((item) => {
              item.name = item.comboServiceName;
              item.num = item.comboServiceCount;
              item.id = item.comboServiceId.toString();
            });
            console.log(res.object.goodList);
            data.serviceList = [...(res.object.goodList || [])];
          }
        });
    };
    const handleChange = () => {
      if (data.searchForm.type == 3) return;
      getTrendData();
    };
    const useTimeChange = (value) => {
      data.orderForm.useDay = value;
      console.log("data.orderForm.useDay", data.orderForm.useDay);
    };
    const upLine = (item) => {
      console.log(item.id);
      console.log(item.status);
      let id = item.id;
      const {closeModal} = useModal.confirm({
        title: `确认上线当前护理卡吗?`,
        icon: createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await api.updateNurseCardStatusAPI({ id });
          console.log(res);
          if (res.success) {
            message.success("上线成功");
            init();
            closeModal()
          }
        },
      });
    };

    const handleActive = (item) => {
      data.number = item.number;
      pages.current = 1;

      initRightList();
      data.jihuoVisible = true;
    };
    const handleLook = (item) => {
      data.editing = false;
      data.title = "查看";
      data.myid = item.number;
      data.active = 0;
      data.activeChart = "activateCount";
      data.chartData = {};
      api
        .selectNurseCardById({
          id: item.id,
        })
        .then((r) => {
          if (r.success) {
            data.visible = true;
            if (r.object.type == 0 || r.object.type == "个人版") {
              r.object.type = "个人版";
            } else {
              r.object.type = "家庭版";
            }
            data.orderForm = {
              ...r.object,
            };
            data.serviceList = [...(r.object.goodList || [])];
          }
        });
    };
    const edit = async (item) => {
      if (item.add) return;
      data.servicesList.map((m) => {
        if (m.id == item.id) {
          m.add = true;
          data.serviceList.push(m);
        }

        return m;
      });
    };
    const Typename = (id) => {
      let item = data.typeList.find((el) => el.id == id);
      console.log(item, "分类名字是");
      return item;
    };

    const serviceName = (id) => {
      let list = data.serviceList.find((el) => el.id == id);
      if (list.serviceName) {
        // return list.serveName;
        return list;
      }
    };
    const changeOrder = (e) => {
      if (e == data.orderAct) return;
      data.orderAct = e;
      pages.current = 1;
      initRightList();
    };
    const save = () => {
      if (data.value.length != 3) {
        message.error("请选择具体服务");
        return;
      }
      data.orderForm.typeId = data.value[0];
      data.orderForm.secondTypeId = data.value[1];
      data.orderForm.serviceId = data.value[2];
      console.log(data.orderForm, "表单内容是");

      formRef.value.validate().then(async () => {
        let arr = [];
        // 查找耗材包明细内容两个数组比较
        data.detaiList.forEach((el) => {
          data.consumables.forEach((item) => {
            if (item == el.id) {
              arr.push(el);
            }
          });
        });
        if (data.value.length == 0) {
          message.error("请选择耗材分类!!!");
          return;
        }

        data.orderForm.consumables = arr;
        let res = await updateAndAddConsumableBag(data.orderForm);
        if (res.success) {
          init();
          message.success("新增成功");
          data.visible = false;
        }
      });
    };
    // 导出数据
    const excleData = () => {
      if (rowSelection.selectedRowKeys.length == 0) {
        message.warning("请选择你要导出的订单");
        return;
      }
      const {closeModal} = useModal.confirm({
        title: `确认导出当前${rowSelection.selectedRowKeys.length}条数据吗?`,

        icon: createVNode(ExclamationCircleOutlined),
        onOk() {
          let obj = {
            ...data.searchForm,
            id: rowSelection.selectedRowKeys.join(",")
          };
          api
            .deriveRedeemCode({
              ...obj,
            })
            .then((res) => {
              console.log(res);
              let link = document.createElement("a");
              //创建一个a标签
              link.style.display = "none";
              //将a标签隐藏
              link.href = res.object;
              //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
              link.setAttribute("download", "订单");
              // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
              document.body.appendChild(link);
              //将上面创建的a标签加入到body的尾部
              link.click();
              closeModal()
            });
          return;
        },
      });
    };
    const addServeVisible = () => {
      pages.current = 1;
      data.serveVisible = true;
      initService();
    };
    // 删除
    const del = (key) => {
      const {closeModal} = useModal.confirm({
        title: () => "你确定删除当前项吗?",
        icon: () => createVNode(QuestionCircleOutlined),
        content: () =>
          createVNode(
            "div",
            {
              style: "color:red;",
            },
            "删除当前数据后不可恢复，请谨慎考虑。"
          ),
        onOk: async () => {
          let res = await deleteConsumableBag([Number(key)]);
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },

        class: "test",
      });
    };
    const selectConsume = (e) => {
      console.log(e);
    };
    const selectService = (e) => {
      // console.log(e, "服务类型");s
    };
    const selectType = (e) => {};



    const { 
				renderData,
				rowSelection,
			} = useSelects({})
    // 删除多项
    const listDel = () => {
      const {closeModal} = useModal.confirm({
        title: "确定删除所选内容项吗?",
        icon: createVNode(ExclamationCircleOutlined),
        content: "删除后将不可恢复，请谨慎操作。",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk: async () => {
          console.log(delListId.value);
          let data = delListId.value.map((el) => (el = Number(el)));

          let res = await deleteConsumableBag(data);
          if (res.success) {
            message.success("删除成功");
            init();
            closeModal()
          }
        },
        
      });
    };
    const handleFreeze = (id) => {
      api
        .updateNurseCardTempStatus({
          id,
          status: 2,
        })
        .then((r) => {
          if (r.success) {
            message.success("操作成功");
            initRightList();
          }
        });
    };
    // 是否上下架 就把原来的状态改变下就行，传递下当前项的耗材ID即可，
    const changeStack = (checked, index, id) => {
      console.log(page.pageNum);
      console.log(checked, index, "是否上下架");
      let title = checked == 0 ? "上架" : "下架";
      // 弹框提示？确定上下架吗
      const {closeModal} = useModal.confirm({
        title: () => `确定${title}当前耗材包吗?`,
        icon: () => createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          let res = await upOrDownConsumableBag(id);
          if (res.success) {
            data.list[index].status = Number(checked);
            init();
          }
        },
        onCancel() {
          let flag = checked == 0 ? 1 : 0;
          data.list[index].status = flag;
        },
        class: "test",
      });
    };

    init();
    const handleSearch = () => {
      initService();
    };
    const saveRight = () => {
      formRef.value.validate().then(() => {
        if (data.serviceList.length == 0) {
          message.error("请选择服务项目");
          return;
        }
        if (data.orderForm.businessPrice == "") {
          message.error("请输入营业额！");
          return;
        }
        if (data.orderForm.useDay == "") {
          message.error("请选择使用时间！");
          return;
        }
        if (data.orderForm.remark == "") {
          message.error("请输入备注！");
          return;
        }

        if (data.orderForm.waitNum == "") {
          message.error("请输入等待期天数（应大于等于30）和选择使用时间！");
          return;
        }
        const reg = /^[1-9]\d*$|^0$/;

        if (reg.test(data.orderForm.waitNum) && data.orderForm.waitNum < 30) {
          message.error("等待期天数应大于等于30！");
          return;
        }

        let goodTempList = data.serviceList.map((m) => {
          return {
            comboServiceCount: m.num,
            comboServiceId: m.id,
            comboServiceName: m.name,
            comboServiceType: "居家护理",
          };
        });
        data.orderForm.useNum = 0;
        goodTempList.forEach((i) => {
          data.orderForm.useNum += i.comboServiceCount;
        });

        // console.log('goodTempList', goodTempList);
        console.log("新增护理卡", data.orderForm);
        if (data.title == "创建") {
          api
            .insertNurseCardTemp({
              ...data.orderForm,
              goodTempList,
            })
            .then((r) => {
              if (r.success) {
                message.success("添加成功");
                data.visible = false;
                page.current = 1;
                init();
              }
            });
        }
        if (data.title == "编辑") {
          let goodList = goodTempList;
          api
            .updateNurseCard({
              ...data.orderForm,
              goodList,
            })
            .then((r) => {
              if (r.success) {
                message.success("编辑成功");
                data.visible = false;
                page.current = 1;
                init();
              }
            });
        }
      });
    };
    async function initService() {
      deleteObjBlank(data.serviceForm);
      api
        .selectServicesByParentIdAndName({
          id: 1,
          ...data.serviceForm,
          ...{
            pageNum: pages.current,
            pageSize: pages.pageSize,
          },
        })
        .then((r) => {
          data.servicesList = r.object.list.map((m) => {
            if (data.serviceList.length > 0) {
              let arr = data.serviceList.filter((v) => v.id == m.id);
              return {
                key: m.id,
                add: arr.length > 0,
                ...m,
                num: 1,
              };
            }
            return {
              key: m.id,
              add: false,
              ...m,
              num: 1,
            };
          });
          pages.total = r.object.total;
          data.visible = true;
        });
    }
    async function initRightList() {
      let obj = {
        pageNum: pages.current,
        pageSize: pages.pageSize,
        status: data.orderAct,
        number: data.number, //机构编号
        ...data.searchForm1,
      };
      let res = await api.selectUserCardByNumber(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.id));
        data.listRights = res.object.list;
        data.loading = false;
        pages.total = res.object.total;
      }
    }
    //列表数据
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm,
      };
      let res = await api.selectOnlineNurseCardList(obj);
      if (res.success) {
        res.object.pagedData.list.map((el) => (el.key = el.number));
        res.object.pagedData.list = res.object.pagedData.list.filter((i) => {
          return i.isTemp == 0;
        });
        data.list = res.object.pagedData.list;
        data.list.forEach((r) => {
          if (r.type == 0 || r.type == "个人版") {
            r.type = "个人版";
          } else {
            r.type = "家庭版";
          }
        });
        data.loading = false;
        page.total = res.object.pagedData.total;
        renderData.value = res.object.allPowerCardIds;
      }
    }
    async function initMy() {
      data.loading = true;
      // 基础数据
      getBaseData();
      // 折线图
      getTrendData();
      data.loading = false;
    }
    async function getBaseData() {}
    const hanldeMyActive = (index) => {
      data.active = index;
      if (index == 1) {
        initMy();
      }
    };
    const closelog = (e, id) => {
      data.serviceList.splice(e, 1);
      data.servicesList.map((m) => {
        if (m.id == id) {
          m.add = false;
        }
        return m;
      });
    };
    const cancleOrder = (v) => {
      data[v] = false;
      if (v == "serveVisible") {
        data.serviceList = [];
      }
    };

    const panelChange = (date, dateString) => {
      data.searchForm.startTime = dateString[0];
      data.searchForm.endTime = dateString[1];
    };
    const panelChange1 = (date, dateString) => {
      console.log("选择的时间是", dateString);
      if (dateString[0]) {
        data.form.startTime = dateString[0];
        data.form.endTime = dateString[1];
      } else {
        data.form = {};
      }
      getTrendData();
    };
    const handleChartActive = (index) => {
      data.activeChart = index;

      data.chartData.yAxis = [];
      data.chartData.xAxis = [];
      data.trendDataAnalysis[index].map((m) => {
        data.chartData.xAxis.push(m.date);

        data.chartData.yAxis.push(m.count);
      });
    };
    async function getTrendData() {
      let obj = {
        type: data.searchForm.type,
        number: data.myid,
      };
      if (data.searchForm.type == 3) {
        obj = {
          ...obj,
          ...data.form,
        };
      }
    }
    const reset = () => {
      data.searchForm = {};
    };
    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);

      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily
      // 二级
      if (selectedOptions.length == 1) {
        let obj = {
          parentId: targetOption.id,
        };
        let res1 = await selectAllType(obj);
        if (res1.success) {
          res1.object.map((el) => (el.isLeaf = false)); //id是string类型的
          targetOption.children = res1.object;
          data.typeList = [...data.typeList];
        }
      } else {
        // 三级
        let obj = {
          pageNum: 1,
          pageSize: 200,
          typeId: targetOption.id,
        };
        let res2 = await selectAllService(obj);
        if (res2.success) {
          res2.object.records.map((el) => (el.name = el.serveName));
          targetOption.children = res2.object.records;
          data.typeList = [...data.typeList];
        }
      }
    };
    return {
      ...retComputed,
      ...toRefs(data),
      saleStatusOptions,
      huliTypeOptions,
      useTimeOptions,
      searchRef,
      formRef,
      rules1,
      columns,
      columns1,
      columns2,
      columns3,
      columnsService,
      pagination,
      paginations,
      labelCol: {
        style: {
          width: "150px",
        },
      },
      wrapperCol: {
        span: 14,
      },
      handleTableChange,
      handleTableChanges,
      handleTableChanges1,
      search,
      searchs,
      add,
      del,
      save,
      cancel,
      edit,
      editHuli,
      rowSelection,
      listDel,
      changeStack,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      addServeVisible,
      closelog,
      cancleOrder,
      changeOrder,
      handleActive,
      // updateNurseCard,
      upLine,
      handleLook,
      panelChange,
      panelChange1,
      handleChange,
      useTimeChange,
      handleSearch,
      saveRight,
      handleFreeze,
      handleChartActive,
      hanldeMyActive,
      excleData,
      reset,
    };
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
  },
};
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}

.header {
  .tab {
    padding: 6px 24px;
    margin-left: 16px;
    background: #eee;
    border-radius: 4px;

    &.active {
      color: #fff;
      background: #006d77;
    }
  }
}

.content {
  display: flex;
  flex-wrap: wrap;

  .cars {
    padding: 9px;
    width: 15%;

    .car {
      .title {
      }

      .nums {
        margin-top: 6px;
        font-size: 24px;
      }
    }
  }
}

.char_wrap {
  width: 90%;
  height: 400px;
}
</style>
